<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport()">导入</el-button>
      </template>
    </avue-crud>
    <el-dialog title="物料负责人导入" :visible.sync="visible" width="555px" append-to-body :close-on-click-modal="false" :close-on-press-escape="false" @close="handleClose">
      <avue-form ref="importConfigForm" v-model="importForm" :option="importConfig.option">
        <template slot="imgUrl">
          <el-upload
            ref="excelFile"
            class="importConfigDialog"
            drag
            action="#"
            :accept="accept"
            limit="1"
            :auto-upload="false"
            :before-remove="handleBeforeRemove"
            :on-change="changeFile"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
              <div v-if="acceptDesc">{{ acceptDesc }}</div>
              <div v-else>请上传{{ accept }}标准格式文件</div>
            </div>
          </el-upload>
        </template>
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleDownLoad()" icon="el-icon-download el-icon--right"> 模板下载 </el-button>
        </template>
      </avue-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small" icon="el-icon-circle-close">取 消</el-button>
        <el-button v-preventReClick type="primary" size="small" @click="saveImport" icon="el-icon-circle-plus-outline">保 存 </el-button>
      </div>
    </el-dialog>
    <el-dialog class="importLogDialog" v-dragDirectives title="导入异常" append-to-body :visible.sync="showImportLogDialog" :close-on-click-modal="false" width="50%">
      <avue-crud :option="importLogOption" :data="importLogData"></avue-crud>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showImportLogDialog = false" size="small" icon="el-icon-circle-close">关 闭</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>
<script>
import { getList, exprot } from '@/api/warehouse/materialManagerConfig';
import { getToken } from '@/util/auth';
import request from '@/router/axios';
export default {
  inject: ['globalStartLoad', 'globalEndLoad'],
  data() {
    return {
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 415px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menu: false,
        selection: true,
        dialogWidth: 880, //弹框宽度属性
        searchLabelWidth: '90',
        dialogClickModal: false,
        columnBtn: false,
        searchSpan: 5,
        column: [
          { label: '物料编码', prop: 'partNo', search: true },
          { label: '物料名称', prop: 'partName', search: true },
          { label: '物料规格', prop: 'partSpec' },
          { label: '物料负责人', prop: 'supervisorName', search: true },
          { label: '更新人', prop: 'updateUserName' },
          {
            label: '更新时间',
            prop: 'updateTime',
            search: true,
            type: 'date',
            searchSpan: 9,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
          }
        ]
      },
      data: [],
      visible: false,
      importForm: {
        imgUrl: {},
        dataRepeat: false
      },
      importConfig: {
        fileLoading: false,
        fileLoadingText: '文件下载中，请稍后...',
        option: {
          emptyBtn: false,
          submitBtn: false,
          labelWidth: 100,
          column: [
            {
              label: '附件上传',
              prop: 'imgUrl',
              type: 'upload',
              loadText: '文件上传中，请稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              data: {},
              headers: {
                'Blade-Auth': getToken()
              },
              tip: '只能上传拓展名为.xls,.xlsx的文件',
              action: '#'
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24
            }
          ]
        }
      },
      importLogOption: {
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        searchSpan: 6,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        menu: false,
        menuWidth: 100,
        columnBtn: false,
        column: [
          {
            label: '行号',
            prop: 'sheetLot'
          },
          {
            label: '原因',
            prop: 'reason'
          }
        ]
      },
      showImportLogDialog: false,
      importLogData: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      if (this.query.updateTime && this.query.updateTime.length > 0) {
        this.query.startTime = this.query.updateTime[0];
        this.query.endTime = this.query.updateTime[1];
        delete this.query.updateTime;
      }
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this._forEach(this.data, (item) => {
          item.status = String(item.status);
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.visible = true;
      this.importForm.dataRepeat = false;
    },
    handleClose() {
      this.$refs.excelFile.clearFiles();
      this.importForm.imgUrl = {};
    },
    changeFile(val) {
      let nameArray = val.name.split('.');
      if (nameArray[nameArray.length - 1] === 'xlsx' || nameArray[nameArray.length - 1] === 'xls') {
        // file保存选择的文件
        this.importForm.imgUrl = val.raw;
      } else {
        this.$message({
          message: '文件格式错误,请确认文件内容并重新上传',
          type: 'warning',
          duration: 2000
        });
      }
    },
    saveImport() {
      if (Object.keys(this.importForm.imgUrl).length == 0) {
        this.$message.warning('请先上传文件后再操作！');
        return;
      }
      const file = this.importForm.imgUrl;
      let fileParams = new FormData();
      fileParams.append('file', file);
      this.globalStartLoad('导入数据中，请稍后...', 'rgba(255,255,255,0.9)');
      let url = `/api/mes-warehouse/material-supervisor/import-excel?continueFlag=${this.importForm.dataRepeat}`;
      request({
        url: url,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: fileParams
      })
        .then((res) => {
          if (res.data.data && res.data.data.length > 0) {
            let repeatPartNo = [];
            let importLogData = [];
            this._forEach(res.data.data, (item) => {
              if (item.type == 5) {
                repeatPartNo.push(item.reason);
              } else {
                importLogData.push(item);
              }
            });
            console.log(importLogData);
            if (repeatPartNo.length > 0) {
              this.$confirm(`以下物料已配置物料负责人，请确认是否继续导入覆盖？物料：${repeatPartNo.join(',')}`, {
                confirmButtonText: '确定导入',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.importForm.dataRepeat = true;
                this.saveImport();
              });
            } else {
              this.showImportLogDialog = true;
              this.importLogData = importLogData;
              this.$refs.importConfigForm.resetFields();
              this.visible = false;
            }
          } else {
            if (res.data.msg) {
              this.$message.success(res.data.msg);
            } else {
              this.$message.success('导入成功');
            }
            this.visible = false;
            this.onLoad(this.page);
            this.$refs.importConfigForm.resetFields();
          }
        })
        .catch((err) => {
          this.$refs.excelFile.clearFiles();
          this.importForm.imgUrl = {};
        })
        .finally(() => {
          this.globalEndLoad();
        });
    },
    async handleBeforeRemove(file, fileList) {
      let res = await this.$confirm(`确定移除 ${file.name}？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (res) {
        this.importForm.imgUrl = {};
        this.$message({
          type: 'success',
          message: '移除成功!'
        });
      }
    },
    async handleDownLoad() {
      let res;
      try {
        const data = {
          originalName: '物料负责人导入模板.xlsx',
          attachType: 'EXCEL'
        };
        res = await exprot({ data });
      } catch (e) {
        const failMsg = await this.blobToJson(e.data);
        this.$message.error(failMsg.msg);
      }
      const blob = new Blob([res.data]);
      const fileName = this.exportName;
      const link = document.createElement('a');
      link.download = fileName;
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.append(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    },
    async blobToJson(blob) {
      return new Promise((resolve, reject) => {
        blob.arrayBuffer().then(
          async (arrayBuffer) => {
            resolve(JSON.parse(Buffer.from(arrayBuffer).toString('utf-8')));
          },
          (error) => {
            reject(error);
          }
        );
      });
    }
  }
};
</script>
